﻿@{
    ViewBag.Title = "VehicleHistory";
    Layout = "~/Views/Shared/_CommonLayout.cshtml";
}
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=XjOymLQ7XokpmPICKh0xlSyw"></script>
<script type="text/javascript" src="~/Scripts/project/MonitorCenterMap.js"></script>
<link type="text/css" rel="stylesheet" href="~/Scripts/My97DatePicker/skin/WdatePicker.css" />
<script type="text/javascript" src="~/Scripts/My97DatePicker/WdatePicker.js"></script>

<script type="text/javascript" src="~/Scripts/jquery-easyui/jquery.easyui.min.js"></script>
<link type="text/css" href="~/Scripts/jquery-easyui/themes/default/easyui.css" rel="stylesheet" />
<link type="text/css" href="~/Scripts/jquery-easyui/themes/icon.css" rel="stylesheet" />

<link type="text/css" href="~/Content/themes/project/loading.css" rel="stylesheet"/>
<style type="text/css">
    body
    {
        display:-moz-box;
        display:-webkit-box;
	    display:box;
        display:-ms-flexbox;
	    -moz-box-orient:vertical;
	    -webkit-box-orient:vertical;
	    box-orient:vertical;
        -ms-flex-direction:column;
    }
</style>
<div id="HistoryTrackDiv" class="MonitorFlexBox-V MonitorFlex-1" style="min-width:1160px;">
    <div id="HistoryTrackWaitingDiv">
        @Html.Partial("~/Views/MonitorCenter/Loading.cshtml")
    </div>
    <input type="hidden" id="BasicInfoInput" value="@ViewBag.InfoModel" />
    <div id="ConditionDiv" class="MonitorFlexBox-H">
        <fieldset id="VehicleCondition">
            <legend>1.车辆条件</legend>
            <div class="MonitorFlexBox-H">
                <input id="VehicleNameInput" type="text" readonly="true"/>
@*                <div id="SelectVehicleDiv" class="ImgButton MonitorFlexBox-H">
                    <img src="~/Images/query.png"  />
                    <span>选择</span>
                </div>*@
            </div>
        </fieldset>
        <fieldset id="TimeCondition">
            <legend>2.时间条件</legend>
            <div class="MonitorFlexBox-H">
                <input id="beginTime" class="Wdate" type="text" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})"/>
                <span>至</span>
                <input id="endTime" class="Wdate" type="text" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})"/>
                <div id="QueryDiv" class="ImgButton MonitorFlexBox-H">
                    <img src="~/Images/query.png"  />
                    <span>查询</span>
                </div>
            </div>
        </fieldset>
        <fieldset id="TrackPath">
            <legend>3.初始化</legend>
            <div id="PaintCheckDiv" style="margin-top:2px;">
                <input type="checkbox" style="vertical-align: middle;" id="PaintCheck" onclick="if (isPlay != 0) { artDialogAlert('请先停止播放历史轨迹'); return false; } else { PaintCheck(this); }" />  初始化路径
            </div>
         </fieldset>
        <fieldset id="PlayOperate">
            <legend>4.播放操作</legend>
            <div class="MonitorFlexBox-H">
                <div id="StartPlay" class="ImgButton MonitorFlexBox-H">
                    <img src="~/Images/start_play.png"  />
                    <span>播放</span>
                </div>
                <div id="PausePlay" class="ImgButton MonitorFlexBox-H">
                    <img src="~/Images/pause_play.png"  />
                    <span id="PauseSpan">暂停</span>
                </div>
                <div id="StopPlay" class="ImgButton MonitorFlexBox-H">
                    <img src="~/Images/stop_play.png" />
                    <span>停止</span>
                </div>
                <div class="MonitorFlexBox-H" style="margin-left:10px;">
                    <div id="MinusDiv" class="ImgButton MonitorFlexBox-H" style="margin-right:10px;">
                        <img src="~/Images/minus.png"  />
                        <span>减速</span>
                    </div>
                    <input id="PlaySliderDiv" value="5" style="width:150px;">
                    <div id="PlusDiv" class="ImgButton MonitorFlexBox-H"  style="margin-left:10px;">
                        <img src="~/Images/plus.png"  />
                        <span>加速</span>
                    </div>
                </div>
            </div>
        </fieldset>
        <div>
            <div><input type="button" value="导出明细数据" onclick="ExportDetailExcel();" /></div>
            <div><input type="button" value="导出停车数据" onclick="ExportStopExcel();" /></div>
        </div>
    </div>
    <div id="ResizableDiv" class="MonitorFlexBox-V">
        <div id="HistoryTrackMapDiv" class="MonitorFlex-1"></div>
    </div>
    <div id="HistoryStatisticDiv" class="MonitorFlexBox-H">
        <span>记录总数: </span><span id="TotalSpan" style="color:white;min-width:120px;text-align:center;"></span>
        <span>行驶时长: </span><span id="DriveTimeSpan" style="color:white;min-width:120px;text-align:center;"></span>
        <span>休息时长: </span><span id="RestTimeSpan" style="color:white;min-width:120px;text-align:center;"></span>
        <span>行驶里程(仪表): </span><span id="DevMileageSpan" style="color:white;min-width:90px;text-align:center;"></span>
        <span>行驶里程(GPS): </span><span id="GpsMileageSpan" style="color:white;min-width:90px;text-align:center;"></span>
        <span>最高速度(GPS): </span><span id="MaxSpeedSpan" style="color:white;min-width:120px;text-align:center;"></span>
        <span>平均速度(GPS): </span><span id="AverageSpeedSpan" style="color:white;min-width:120px;text-align:center;"></span>
    </div>
    <div id="HistoryTabDiv" class="MonitorFlex-1">
        <div title="明细数据" style="padding-bottom:10px;">
            <table id="DetailDataTable" class="easyui-datagrid"
                rownumbers="true"
                singleSelect="true"
                striped="true"
                loadMsg=""
                fit="true"
                pagination="true"
                pageSize="20"
                data-options="onDblClickRow:OnDblClickRow">
                <thead>
                    <tr>
                        <th field="name">车牌号</th>
                        <th field="sim">SIM卡号</th>
                        <th field="depart">所属单位</th>
                        <th field="lng">经度</th>
                        <th field="lat">纬度</th>
                        <th field="addr">地址</th>
                        <th field="gpsSpeed">GPS速度</th>
                        <th field="gpsMileage">GPS里程</th>
                        <th field="devSpeed">仪表速度</th>
                        <th field="devMileage">仪表里程</th>
                        <th field="oil">油量</th>
                        <th field="state0">ACC</th>
                        <th field="state41">正反转</th>
                        <th field="dire">方向</th>
                        <th field="time">上传时间</th>
                    </tr>
                </thead>
            </table>
        </div>
        @*<div title="速度分析">
            
        </div>
        <div title="报警地点" style="padding-bottom:10px;">
            <table id="WarnTable" class="easyui-datagrid"
                fitColumns="true"
                rownumbers="true"
                singleSelect="true"
                striped="true"
                loadMsg=""
                fit="true">
                <thead>
                    <tr>
                        <th field="name">报警时间</th>
                        <th field="sim">报警持续时间</th>
                        <th field="depart">报警类型</th>
                        <th field="lng">报警原因</th>
                        <th field="lat" width="5000">报警地点</th>
                    </tr>
                </thead>
            </table>
        </div>*@
        <div title="停车地点">
            <table id="ParkTable" class="easyui-datagrid"
                fitColumns="true"
                rownumbers="true"
                singleSelect="true"
                striped="true"
                loadMsg=""
                pagination="true"
                pageSize="20"
                idField="id"
                fit="true"
                data-options="onDblClickRow:OnDblClickRowPark">
                <thead>
                    <tr>
                        <th field="beginTime">开始时间</th>
                        <th field="endTime">结束时间</th>
                        <th field="interval">停车时长</th>
                        <th field="addr" width="5000">停车位置</th>
                    </tr>
                </thead>
            </table>
        </div>
        @*<div title="超速路段">
            <table id="OverspeedTable" class="easyui-datagrid"
                fitColumns="true"
                rownumbers="true"
                singleSelect="true"
                striped="true"
                loadMsg=""
                fit="true">
                <thead>
                    <tr>
                        <th field="name">开始时间</th>
                        <th field="sim">结束时间</th>
                        <th field="depart">超速时长</th>
                        <th field="lng">开始位置</th>
                        <th field="lat" width="5000">结束位置</th>
                    </tr>
                </thead>
            </table>
        </div>
        <div title="上下线明细">
            <table id="OnlineTable" class="easyui-datagrid"
                fitColumns="true"
                rownumbers="true"
                singleSelect="true"
                striped="true"
                loadMsg=""
                fit="true">
                <thead>
                    <tr>
                        <th field="name">上线时间</th>
                        <th field="sim">上线地点</th>
                        <th field="depart">下线时间</th>
                        <th field="lng" width="5000">下线地点</th>
                    </tr>
                </thead>
            </table>
        </div>*@
    </div>
    <form id="exportForm" name="exportForm" method="post">
        <input type="hidden" id="name" name="name"/>
        <input type="hidden" id="sim" name="sim"/>
        <input type="hidden" id="depart" name="depart"/>
        <input type="hidden" id="data" name="data"/>
    </form>

</div>
<script type="text/javascript">
    var basicInfo;
    var isLoading = false;
    var isPlay = 0;//0未播放（停止），1播放，2暂停
    var historyData = null;
    var stopData = null;
    var poikey;
    var parseTimer;
    var paintPath = false;//是否一开始就绘制路径
    $(document).ready(function () {
        InitBaiduMap("武汉市", 14, "HistoryTrackMapDiv", false);
        InitResizable();
        InitSlider();
        InitTabs();
        InitDataGrid();
        InitPlayMenu();
        //窗口放大缩小时
        $(window).resize(function () {
            InitResizable();
        });

        basicInfo = $.parseJSON($("#BasicInfoInput").val());
        $("#VehicleNameInput").val(basicInfo.name);

        $("#QueryDiv").click(function () {
            GetHistoryGpsData();
        });

        setTimeout(function () {
            $("#HistoryTrackWaitingDiv").hide();
        }, 3000);
    });
    //初始化DataGrid
    function InitDataGrid() {
        InitPager($('#DetailDataTable'));
        InitPager($("#ParkTable"));
    }
    //初始化分页控件
    function InitPager(dg) {
        var pager = dg.datagrid('getPager');
        pager.pagination({
            pageSize: 20,//每页显示的记录条数，默认为10  
            beforePageText: '第',//页数文本框前显示的汉字  
            afterPageText: '页，共{pages}页',
            displayMsg: '当前显示{from}到{to}条记录，共{total}条记录',
            layout: ["first", "prev", "sep", "manual", "sep", "next", "last"]
        });
    }
    //初始化Tab菜单
    function InitTabs() {
        $("#HistoryTabDiv").tabs({
            border: false,
            height: $("#HistoryTabDiv").height()
        });
        $("#HistoryTabDiv").tabs("select", "停车地点");
        $("#HistoryTabDiv").tabs("select", "明细数据");
    }
    //初始化播放速度
    function InitSlider() {
        $("#PlaySliderDiv").slider({
            showTip: true,
            min: 1,
            max: 10,
            tipFormatter: function (value) {
                return value;
            },
            onSlideEnd: OnSlideEnd
        });
        $("#MinusDiv").click(function () {
            var value = $("#PlaySliderDiv").slider("getValue");
            if (value > 1) {
                $("#PlaySliderDiv").slider("setValue", value - 1);
                SetSpeed(value - 1, isPlay);
            }
        });
        $("#PlusDiv").click(function () {
            var value = $("#PlaySliderDiv").slider("getValue");
            if (value < 10) {
                $("#PlaySliderDiv").slider("setValue", value + 1);
                SetSpeed(value + 1, isPlay);
            }
        });
    }
    /*是否一开始绘制路径*/
    function PaintCheck(object) {

        var old = $(object).attr("checked");
        if (old == "checked") {
            SetPaintPath(true);
            paintPath = true;
        }
        else {
            SetPaintPath(false);
            paintPath = false;
        }
    }
    /*速度slider拖动结束*/
    function OnSlideEnd(value) {
        SetSpeed(value, isPlay);
    }
    /*初始播放菜单*/
    function InitPlayMenu() {
        $("#StartPlay").click(function () {
            if (isPlay == 1 || isPlay == 2) {
                artDialogAlert("历史轨迹已经开始播放");
                return;
            }
            if (isLoading == true) {
                artDialogAlert("历史轨迹数据正在加载...");
                return;
            }
            if (historyData == null) {
                artDialogAlert("请先查询历史轨迹数据...");
                return;
            }
            isPlay = 1;
            StartTrackBack();
        });
        $("#PausePlay").click(function () {
            if (isPlay == 1) {
                isPlay = 2;
                $("#PauseSpan").html("继续");
                PauseTrackBack();
            }
            else if (isPlay == 2) {
                isPlay = 1;
                $("#PauseSpan").html("暂停");
                ContinueTrackBack();
            }
        });
        $("#StopPlay").click(function () {
            if (isPlay == 1 || isPlay == 2) {
                isPlay = 0;
                StopTrackBack();
            }
            $("#PauseSpan").html("暂停");
        });
    }
    //初始化resizable
    function InitResizable() {
        var height = $("#HistoryTrackDiv").height() - $("#ConditionDiv").height() - $("#HistoryStatisticDiv").height() - 30;
        $("#ResizableDiv").height(height * 3 / 4);
        $("#ResizableDiv").resizable({
            minHeight: 10,
            maxHeight: height,
            handles: "s",
            onStopResize: OnResize
        });
        // OnResize();
    }
    //onResize
    function OnResize() {
        var oldTabHeight = $("#HistoryTabDiv").height();
        $(".tabs-panels").height(oldTabHeight - 37);
        $(".tabs-panels > .panel").height(oldTabHeight - 37);
        $(".tabs-panels > .panel > .panel-body").height(oldTabHeight - 37);
        var newWidth = $("#HistoryTabDiv").width() - 30;
        var newHeight = oldTabHeight - 30;
        $("#DetailDataTable").datagrid("resize", {
            width: newWidth,
            height: newHeight
        });
        $("#WarnTable").datagrid("resize", {
            width: newWidth,
            height: newHeight
        });
        $("#ParkTable").datagrid("resize", {
            width: newWidth,
            height: newHeight
        });
        $("#OverspeedTable").datagrid("resize", {
            width: newWidth,
            height: newHeight
        });
        $("#OnlineTable").datagrid("resize", {
            width: newWidth,
            height: newHeight
        });
    }
    /*时间格式是否正确*/
    function TimeValidate() {
        var beginTime = $("#beginTime").val();
        var endTime = $("#endTime").val();
        if (beginTime == "" || endTime == "" ||
            beginTime == null || endTime == null) {
            artDialogAlert("时间格式不合法！");
            return false;
        }
        //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式
        beginTime = beginTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        var sTime = new Date(beginTime);      //开始时间
        var eTime = new Date(endTime);  //结束时间
        var tmp = parseInt(eTime.getTime() - sTime.getTime());
        if ((tmp / parseInt(1000 * 3600 * 24)) > 31) {
            artDialogAlert("只能查询一个月内的历史轨迹！");
            return false;
        }
        else if (tmp <= 0) {
            artDialogAlert("开始时间不能大于等于结束时间！");
            return false;
        }
        else {//时间合法
            return true;
        }
    }
    /*查询历史轨迹数据*/
    function GetHistoryGpsData() {
        if (isPlay == 1 || isPlay == 2) {
            artDialogAlert("历史轨迹正在播放，请先停止播放");
            return;
        }
        isPlay = 0;
        if (TimeValidate()) {
            if (isLoading == true) {
                artDialogAlert("正在加载，请稍后...");
                return;
            }
            isLoading = true;
            var beginTime = $("#beginTime").val();
            var endTime = $("#endTime").val();

            $("#HistoryTrackWaitingDiv").show();
            $.ajax({
                type: "post",
                url: "/MonitorCenter/GetHistoryGpsData",
                data: {
                    "beginTime": beginTime,
                    "endTime": endTime,
                    "vehicleNum": basicInfo.id
                },
                traditional: true,
                success: function (data) {
                    if (data != "" && data != null && data.total != 0) {
                        for (var i = 0; i < data.rows.length; i++) {
                            //基础信息赋值
                            data.rows[i].name = basicInfo.name;
                            data.rows[i].depart = basicInfo.depart;
                        }
                        historyData = data.rows;
                        InitStatisticData();//统计并过滤数据
                        data.rows = historyData;
                        data.total = historyData.length;
                        InitTrackBack(data.rows, paintPath);//初始化地图 
                        $("#DetailDataTable").datagrid("loadData", { total: 0, rows: [] });
                        $('#DetailDataTable').datagrid({ loadFilter: pagerFilter }).datagrid('loadData', data);
                        $('#DetailDataTable').datagrid("getPager").pagination('select', 1);
                        historyData = data.originalRows;
                        poikey = (new Date).getTime() + "" ;
                        ParseAddr(1); 
                    }
                    else {
                        $("#DetailDataTable").datagrid("loadData", { total: 0, rows: [] });
                        historyData = null;
                        if (data != null && data.total == 0) {
                            artDialogAlert("没有这个时间段的数据");
                        }
                        else {

                        }
                    }
                    $("#HistoryTrackWaitingDiv").hide();
                    isLoading = false;
                },
                error: function (XMLHttpRequest) {
                    $("#HistoryTrackWaitingDiv").hide();
                    isLoading = false;
                    artDialogAlert("加载错误，错误代码：" + XMLHttpRequest.status);
                }
            });
        }
    }
    //双击实时数据,获取焦点
    function OnDblClickRow(rowIndex, rowData) {
        var opts = $("#DetailDataTable").datagrid('options');
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        FocusBackMarker(start + rowIndex);
    }
    //双击停车点，获取焦点
    function OnDblClickRowPark(rowIndex, rowData) {
        var opts = $("#DetailDataTable").datagrid('options');
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        FocusBackMarker(start + rowData.id);
    }
    //解析地理位置
    function ParseAddr(index) {
        var options = $('#DetailDataTable').datagrid('getPager').data("pagination").options;
        var total = options.total;
        var curPage = options.pageNumber;
        var pageSize = options.pageSize;
        var pages = Math.ceil(options.total / options.pageSize);
        if (index <= pages) {
            var sIndex = (index - 1) * pageSize;
            var lngs = [];
            var lats = [];
            var length = 0;
            if (index < pages) {
                length = pageSize;
            }
            else {
                length = total - sIndex;
            }
            for (var j = 0; j < length; j++) {
                lngs.push(historyData[sIndex + j].lng);
                lats.push(historyData[sIndex + j].lat);
            }
            $.ajax({
                type: "post",
                url: "/MonitorCenter/ParseAddr",
                data: {
                    "lngs": lngs,
                    "lats": lats,
                    "key": poikey,
                    "page": index
                },
                traditional: true,
                success: function (data) {
                    if (data != null) {
                        var retPage = data.page;
                        var retKey = data.key;
                        var retPois = data.pois;
                        if (retKey == poikey) {//校验正确
                            var retsIndex = (retPage - 1) * pageSize;
                            for (var j = 0; j < length; j++) {
                                historyData[retsIndex + j].addr = retPois[j];
                                UpdateBackInfoWindow(retsIndex + j, historyData[retsIndex + j]);
                            }
                            if (retPage == options.pageNumber) {//当前页
                                $('#DetailDataTable').datagrid("getPager").pagination('select', retPage);//刷新当前页数据
                            }
                            UpdateStatisticData(data, retsIndex);
                            ParseAddr(++index);
                        }
                    }
                }
            });
            //parseTimer = setTimeout(function () {
            //    ParseAddr(++index);
            //}, 500);
        }
    }
    /*初始化统计数据*/
    function InitStatisticData() {
        var maxSpeed = 0;//最大速度
        var averageSpeed = 0;//平均速度
        var stopPreIndex = -1;//停车点
        var filterStopPreIndex = -1;//数据过滤后停车点所在索引
        var accCloseIndex = -1;//acc关闭点
        var restTime = 0;//累计休息时间
        var stopDataRows = [];//停车点行数据
        var filterRow = [];//过滤0速度点后的数据
        if (historyData != null) {
            for (var i = 0; i < historyData.length; i++) {
                var row = historyData[i];
                if (row.state0 == "关" && accCloseIndex == -1) {
                    //acc关闭点
                    accCloseIndex = i;
                }
                if (row.state0 == "开" && accCloseIndex != -1) {
                    //acc启动点
                    restTime += CaculateTime2(historyData[accCloseIndex].time, historyData[i].time);
                    accCloseIndex = -1;
                }
                var speed = parseFloat(row.gpsSpeed);
                if (maxSpeed < speed) {
                    maxSpeed = speed;
                }
                if (speed == 0 && stopPreIndex == -1) {
                    //第一个停车点
                    filterRow.push(row);
                    filterStopPreIndex = filterRow.length - 1;
                    stopPreIndex = i;
                }
                if ((speed != 0 && stopPreIndex != -1) || (speed == 0 && stopPreIndex != -1 && i == historyData.length - 1)) {
                    //停车结束点
                    stopDataRows.push({
                        id: filterStopPreIndex,
                        beginTime: historyData[stopPreIndex].time,
                        endTime: historyData[i].time,
                        addr: historyData[stopPreIndex].addr,
                        interval: CaculateTime(historyData[stopPreIndex].time, historyData[i].time)
                    });
                    stopPreIndex = -1;
                }
                averageSpeed += speed;
                if (speed != 0) {
                    filterRow.push(row);
                }
            }
            averageSpeed /= historyData.length;
            var tmpMaxSpeed = maxSpeed.toFixed(2);
            $("#MaxSpeedSpan").html(tmpMaxSpeed == "NaN" ? "" : (tmpMaxSpeed + " 公里/小时"));
            var tmpAverageSpeed = averageSpeed.toFixed(2);
            $("#AverageSpeedSpan").html(tmpAverageSpeed == "NaN" ? "" : (tmpAverageSpeed + " 公里/小时"));
            var gpsTotalMileage = (parseFloat(historyData[historyData.length - 1].gpsMileage)
                - parseFloat(historyData[0].gpsMileage)).toFixed(2);
            $("#GpsMileageSpan").html(gpsTotalMileage == "NaN" ? "" : (gpsTotalMileage + " 公里"));
            var devTotalMileage = (parseFloat(historyData[historyData.length - 1].devMileage)
                - parseFloat(historyData[0].devMileage)).toFixed(2);
            $("#DevMileageSpan").html(devTotalMileage == "NaN" ? "" : (devTotalMileage + " 公里"));
            $("#RestTimeSpan").html(CaculateTime3(restTime));
            $("#DriveTimeSpan").html(CaculateTime3(CaculateTime2(historyData[0].time, historyData[historyData.length - 1].time) - restTime));
            $("#TotalSpan").html(filterRow.length);
            /*停车地点*/
            stopData = stopDataRows;
            $("#ParkTable").datagrid("loadData", { total: 0, rows: [] });
            $('#ParkTable').datagrid({ loadFilter: pagerFilter }).datagrid('loadData', {
                total: stopDataRows.length,
                rows: stopDataRows
            });
            $('#ParkTable').datagrid("getPager").pagination('select', 1);
            historyData = filterRow;
        }
    }
    /*更新统计信息*/
    function UpdateStatisticData(data, startIndex) {
        for (var i = 0; i < data.pois.length; i++) {
            for (var j = 0; j < stopData.length; j++) {
                if (stopData[j].id == startIndex + i) {
                    stopData[j].addr = data.pois[i];
                    break;
                }
            }
            var rowIndex = $("#ParkTable").datagrid("getRowIndex", startIndex + i + "");
            if (rowIndex >= 0) {//在当前页
                $("#ParkTable").datagrid("refreshRow", rowIndex);
            }
        }
    }
    /*计算时间差*/
    function CaculateTime(beginTime, endTime) {
        var tmp = CaculateTime2(beginTime, endTime)
        return CaculateTime3(tmp);
    }
    function CaculateTime2(beginTime, endTime) {
        beginTime = beginTime.replace(/\-/g, "/");
        endTime = endTime.replace(/\-/g, "/");
        var sTime = new Date(beginTime); //开始时间
        var eTime = new Date(endTime);  //结束时间
        return parseInt(eTime.getTime() - sTime.getTime());
    }
    function CaculateTime3(tmp) {
        var days = Math.floor(tmp / (24 * 3600 * 1000))
        //小时数
        var leave1 = tmp % (24 * 3600 * 1000)//计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //分钟数
        var leave2 = leave1 % (3600 * 1000)//计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        return days + "天" + hours + "时" + minutes + "分" + seconds + "秒";
    }

    /*获得当前播放条目焦点*/
    function FocusRow(index) {
        var options = $('#DetailDataTable').datagrid('getPager').data("pagination").options;
        var curPage = options.pageNumber;//当前所在页
        var pageSize = options.pageSize;
        var total = options.total;
        var tmpPage = Math.ceil(index / pageSize);//实际需要显示的页
        var tmpOffset = (tmpPage - 1) * pageSize;//偏移量

        if (index % 20 == 0) {
            //如果要显示的是下一页的第一条，先暂停，跳页完成后再开始
            if (tmpPage != 1) {
                PauseTrackBack();
                $('#DetailDataTable').datagrid("getPager").pagination('select', tmpPage + 1);
                $("#DetailDataTable").datagrid("selectRow", index - tmpOffset);
                $("#DetailDataTable").datagrid("scrollTo", index - tmpOffset);
                ContinueTrackBack();
            }
            else {
                $("#DetailDataTable").datagrid("selectRow", index);
                $("#DetailDataTable").datagrid("scrollTo", index);
            }
        }
        else {
            if (curPage != tmpPage) {//当前页与需要显示的页不相等，跳到需要显示的页
                PauseTrackBack();
                $('#DetailDataTable').datagrid("getPager").pagination('select', tmpPage);
                ContinueTrackBack();
            }
            $("#DetailDataTable").datagrid("selectRow", index - tmpOffset);
            $("#DetailDataTable").datagrid("scrollTo", index - tmpOffset);
        }
        if (index + 1 == total) {
            isPlay = 0;//停止播放
        }
    }
    /*本地分页*/
    function pagerFilter(data) {
        if (typeof data.length == 'number' && typeof data.splice == 'function') {    // is array
            data = {
                total: data.length,
                rows: data
            }
        }
        var dg = $(this);
        var opts = dg.datagrid('options');
        var pager = dg.datagrid('getPager');
        pager.pagination({
            pageSize: 20,//每页显示的记录条数，默认为10  
            beforePageText: '第',//页数文本框前显示的汉字  
            afterPageText: '页，共{pages}页',
            displayMsg: '当前显示{from}到{to}条记录，共{total}条记录',
            layout: ["first", "prev", "sep", "manual", "sep", "next", "last"],
            onSelectPage: function (pageNum, pageSize) {
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh', {
                    pageNumber: pageNum,
                    pageSize: pageSize
                });
                dg.datagrid('loadData', data);
            }
        });
        if (!data.originalRows) {
            data.originalRows = (data.rows);
        }
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = (data.originalRows.slice(start, end));
        return data;
    }

    function ExportDetailExcel() {
        if (historyData != null && historyData.length != 0) {
            var name = historyData[0].name;
            var sim = historyData[0].sim;
            var depart = historyData[0].depart;
            var gps = [];
            for (var i = 0; i < historyData.length; i++) {
                var item = {
                    "lng": historyData[i].lng,
                    "lat": historyData[i].lat,
                    "addr": historyData[i].addr,
                    "gpsSpeed": historyData[i].gpsSpeed,
                    "gpsMileage": historyData[i].gpsMileage,
                    "devSpeed": historyData[i].devSpeed,
                    "devMileage": historyData[i].devMileage,
                    "oil": historyData[i].oil,
                    "acc": historyData[i].state0,
                    "reverse": historyData[i].state41,
                    "dirc": historyData[i].dirc,
                    "time": historyData[i].time,
                }
                gps.push(item);
            }
            $("#name").val(name);
            $("#sim").val(sim);
            $("#depart").val(depart);
            $("#data").val(JSON.stringify(gps));
            $("#exportForm").attr("action", "/MonitorCenter/ExportExcel");
            $("#exportForm").submit();
        }
    }


    function ExportStopExcel() {
        if (stopData != null && stopData.length != 0) {
            var name = historyData[0].name;
            var sim = historyData[0].sim;
            var depart = historyData[0].depart;
            var stop = [];
            for (var i = 0; i < stopData.length; i++) {
                var item = {
                    "startTime": stopData[i].beginTime,
                    "endTime": stopData[i].endTime,
                    "interval": stopData[i].interval,
                    "addr": stopData[i].addr
                }
                stop.push(item);
            }
            $("#name").val(name);
            $("#sim").val(sim);
            $("#depart").val(depart);
            $("#data").val(JSON.stringify(stop));
            $("#exportForm").attr("action", "/MonitorCenter/ExportStopExcel");
            $("#exportForm").submit();
        }
    }
</script>
